const express = require('express');
const { ObjectId } = require('mongodb');
const { getTagCollection } = require('./database');

const router = express.Router();

// 中间件，用于获取 tagCollection
router.use(async (req, res, next) => {
    req.tagCollection = await getTagCollection();
    next();
});

router.post('/tags', async (req, res) => {
    // 创建标签的逻辑
    try {
        console.log("req.body", req.body)
        const result = await req.tagCollection.insertOne(req.body);
        res.status(201).json({ message: 'Tag created successfully', tagId: result.insertedId });
    } catch (err) {
        console.log(err)
        res.status(500).json({ message: 'Error creating tag', err });
    }
});

router.put('/tags/:id', async (req, res) => {
    // 更新标签的逻辑
    try {
        const result = await req.tagCollection.updateOne({ _id: new ObjectId(req.params.id) }, { $set: req.body });
        res.json({ message: 'Tag updated successfully' });
    } catch (err) {
        res.status(500).json({ message: 'Error updating tag' });
    }
});

router.get('/tags', async (req, res) => {
    // 获取标签列表的逻辑
    try {
        const tags = await req.tagCollection.find().toArray();
        res.json(tags);
    } catch (err) {
        res.status(500).json({ message: 'Error fetching tags' });
    }
});

router.get('/tags/:id', async (req, res) => {
    // 获取特定标签的逻辑
    try {
        const tag = await req.tagCollection.findOne({ _id: new ObjectId(req.params.id) });
        if (!tag) {
            return res.status(404).json({ message: 'Tag not found' });
        }
        res.json(tag);
    } catch (err) {
        res.status(500).json({ message: 'Error fetching tag' });
    }
});

router.delete('/tags/:id', async (req, res) => {
    // 删除标签的逻辑
    try {
        const result = await req.tagCollection.deleteOne({ _id: new ObjectId(req.params.id) });
        if (result.deletedCount === 0) {
            return res.status(404).json({ message: 'Tag not found' });
        }
        res.json({ message: 'Tag deleted successfully' });
    } catch (err) {
        res.status(500).json({ message: 'Error deleting tag' });
    }
});

module.exports = router;